package com.fdq.bigevent.controller;

import com.fdq.bigevent.pojo.Result;
import com.fdq.bigevent.pojo.User;
import com.fdq.bigevent.service.Imp.UserServiceImp;
import com.fdq.bigevent.service.UserService;
import com.fdq.bigevent.util.JwtUtil;
import com.fdq.bigevent.util.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,10}$")String password){
       return userService.register(username,password);
    }

    @PostMapping("/login")
    Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,10}$")String password){
        return userService.login(username, password);
    }

    //根据用户名查找用户
    @GetMapping("/userInfo")
    Result<User> userInfo(){
        Map<String, Object> userToken = ThreadLocalUtil.get();
        String username =(String) userToken.get("username");
        User user = userService.findUserByName(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    Result update(@RequestBody @Validated User user){
        return userService.update(user);
    }

    @PatchMapping("/updateAvatar")
    Result updateAvatar(@RequestParam @URL String avatarUrl){
        return userService.updateAvatar(avatarUrl);
    }

    @PatchMapping("/updatePwd")
    Result updatePwd(@RequestBody Map<String, String> params){
        //参数检验
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if(oldPwd.equals("") || newPwd.equals("") || rePwd.equals("")){
            return Result.error("密码不能为空");
        }
        if(!newPwd.equals(rePwd)){
            return Result.error("两次新密码不一样");
        }

        return userService.updatePwd(oldPwd,newPwd);
    }
}
